//
//  AppDelegate.m
//  lianganyuchu
//
//  Created by iMac on 17/2/9.
//  Copyright © 2017年 杭州桑缇电子商务有限公司. All rights reserved.
//

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate
+ (AppDelegate *)appDelegate; {
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = WHITE_COLOR;
    self.window.autoresizesSubviews = YES;
    [self.window makeKeyAndVisible];
    
    //极光推送
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    [JPUSHService setupWithOption:launchOptions appKey:JPushAppKey
                          channel:@"App Store"
                 apsForProduction:1
            advertisingIdentifier:advertisingId];
    
    
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        [App shared].deviceToken = registrationID;
        [[App shared] saveDeviceToken];
        [[App shared] readDeviceToken];
    }];

    
    [[App shared] restore];
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstRun"]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstRun"];
        [self loadLogin];
    }else{
        [self loadLogin];
    }

    
    return YES;
}
-(void)loadLogin
{
    App *app = [App shared];
    if ([app isUserLogin]){
        self.window.rootViewController=[[YCTabBarViewController alloc]init];
        
        NSUserDefaults  *userDefault = [NSUserDefaults standardUserDefaults];
        NSString *uuidString = [userDefault stringForKey:@"uuidstring"];
        if (uuidString.length>0) {
            [self connectPrint];
        }
    }else {
        [self loginOut];
    }
}
-(void)loginOut
{
    YCLoginViewController *loginVC=[[YCLoginViewController alloc]init];
    YCNavigationViewController *navi=[[YCNavigationViewController alloc]initWithRootViewController:loginVC];
    self.window.rootViewController=navi;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [self testRemoveAllNotification];
    
    NSNotification *notification =[NSNotification notificationWithName:@"keyboardShow" object:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
}
- (void)testRemoveAllNotification
{
    [JPUSHService removeNotification:nil];
    [JPUSHService setBadge:0];
    [[UIApplication sharedApplication]setApplicationIconBadgeNumber:0];
}


- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [self testRemoveAllNotification];
    
    NSNotification *notification =[NSNotification notificationWithName:@"reloadOrder" object:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}  

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    if (application.applicationState == UIApplicationStateActive) {
        CBWAlertView *view = [[CBWAlertView alloc]initWithTitle:@"提示" andMessage:@"您有新的订单"];
        view.animationType = AnimationTypeBigToSmall;
        view.titleTextColor = TEXT_DEEP;
        [view addButtonWithTitle:@"取消" color:BLUE_COLOR handler:^(CBWAlertView *alertView){
        }];
        [view addButtonWithTitle:@"查看" color:BLUE_COLOR handler:^(CBWAlertView *alertView) {
        }];
        [view show];
    }else{
        // 处于后台 的点击        
    }
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}

-(void)showDetailVC
{
    //    YCOrderDetailViewController *detailVC=[[YCOrderDetailViewController alloc]initWithPopBack:YES];
    //    [[self currentViewController].navigationController pushViewController:detailVC animated:YES];
}
- (UIViewController *)currentViewController{
    UIViewController *currVC =nil;
    UIViewController *Rootvc =self.window.rootViewController;
    do{
        if ([Rootvc isKindOfClass:[UINavigationController class]]) {
            UINavigationController *nav = (UINavigationController *)Rootvc;
            UIViewController *v = [nav.viewControllers lastObject];
            currVC = v;
            Rootvc = v.presentedViewController;
            continue;
        }else if ([Rootvc isKindOfClass:[UITabBarController class]]){
            UITabBarController *tabvc = (UITabBarController *)Rootvc;
            currVC = tabvc;
            Rootvc = [tabvc.viewControllers objectAtIndex:tabvc.selectedIndex];
            continue;
        }
        
    }while (Rootvc !=nil);
    return currVC;
}

-(void)connectPrint
{
    SEPrinterManager *_printManager = [SEPrinterManager sharedInstance];
    [_printManager startScanPerpheralTimeout:3 Success:^(NSArray<CBPeripheral *> *perpherals,BOOL isTimeout) {
        NSUserDefaults  *userDefault = [NSUserDefaults standardUserDefaults];
        NSString *uuidString = [userDefault stringForKey:@"uuidstring"];
        for (CBPeripheral *peripheral in perpherals) {
            if ([peripheral.identifier.UUIDString isEqualToString:uuidString]) {
                [[SEPrinterManager sharedInstance] connectPeripheral:peripheral completion:^(CBPeripheral *perpheral, NSError *error) {
                    if (error) {
                    } else {
                    }
                    [userDefault setValue:@"yes" forKey:@"printOn"];
                }];
            }
        }
    } failure:^(SEScanError error) {
        if (error==SEScanErrorTimeout) {
            NSUserDefaults  *userDefault = [NSUserDefaults standardUserDefaults];
            [userDefault setValue:@"no" forKey:@"printOn"];
        }
    }];
    
}

@end



